//
//  UIView+Empty.m
//  Foundation
//
//  Created by 三井 on 2019/10/15.
//

#import "UIView+Empty.h"
#import "FViewEmptyItem.h"
#import "FViewEmptyContainer.h"

static NSString * const kFViewEmptyKey = @"kFViewEmptyKey";
@interface UIView ()

@property (nonatomic, strong) FViewEmptyItem *emptyItem;

@end

@implementation UIView (Empty)

- (NSString *)emptyInfo {
    return self.emptyItem.info;
}

- (void)setEmptyInfo:(NSString *)emptyInfo {
    self.emptyItem.info = emptyInfo;
}

- (UIEdgeInsets)emptyInsets {
    return self.emptyItem.insets;
}

- (void)setEmptyInsets:(UIEdgeInsets)emptyInsets {
    self.emptyItem.insets = emptyInsets;
}

- (UIImage *)emptyImage {
    return self.emptyItem.image;
}

- (void)setEmptyImage:(UIImage *)emptyImage {
    self.emptyItem.image = emptyImage;
}

- (UIView *)emptyView {
    return self.emptyItem.view;
}

- (void)setEmptyView:(UIView *)emptyView {
    self.emptyItem.view = emptyView;
}

- (void)setControl:(NSString *)title handler:(void (^)(UIView * _Nonnull))handler {
    self.emptyItem.controlTitle = title;
    self.emptyItem.controlEventHandler = handler;
}

- (void)emptyShow:(BOOL)visible {
    [self layoutViews];
    
    if (visible) {
        self.emptyItem.container.hidden = NO;
    } else {
        self.emptyItem.container.hidden = YES;
    }
}

#pragma mark - Action
- (void)clickControl:(UIButton *)btn {
    !self.emptyItem.controlEventHandler ?: self.emptyItem.controlEventHandler(self);
}

#pragma mark - Private
- (void)layoutViews {
    if (!self.emptyItem.container.superview) {
        [self addSubview:self.emptyItem.container];
        [self.emptyItem.container mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_offset(0);
            make.top.mas_offset(UIScreen.jk_height * 0.3);
        }];
    }
    self.emptyItem.container.image = self.emptyItem.image;
    self.emptyItem.container.info = self.emptyInfo;
    
    // control
    if (self.emptyItem.controlTitle.length > 0) {
        self.emptyItem.container.userInteractionEnabled = YES;
        self.emptyItem.container.controlButton.hidden = NO;
        [self.emptyItem.container.controlButton setTitle:self.emptyItem.controlTitle forState:UIControlStateNormal];
        [self.emptyItem.container.controlButton addTarget:self action:@selector(clickControl:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        self.emptyItem.container.controlButton.hidden = YES;
    }
}

- (FViewEmptyItem *)emptyItem {
    FViewEmptyItem *item = [self jk_associatedValueForKey:(__bridge void *)(kFViewEmptyKey)];
    if (!item) {
        item = [[FViewEmptyItem alloc] init];
        self.emptyItem = item;
    }
    return item;
}

- (void)setEmptyItem:(FViewEmptyItem *)emptyItem {
    [self jk_associateValue:emptyItem withKey:(__bridge void *)(kFViewEmptyKey)];
}

@end
